import React, { Component } from 'react';
import DataBinder from '@icedesign/data-binder';
import { Dialog, Message } from '@alifd/next';
import { pageableResponseFormatter, defaultBindingData } from '#/utils/coreApiDefine';

export default (url, opts) => WrappedComponent => {
  opts = opts || {}
  @DataBinder({
    instances: {
      url: '/databus' + url,
      type: 'get',
      // 格式化API返回数据，匹配DataBinder数据规范
      responseFormatter: opts.responseFormatter ? opts.responseFormatter : pageableResponseFormatter,
      defaultBindingData: opts.defaultBindingData ? opts.defaultBindingData : defaultBindingData,
    }
  })
  class SearchTableWrapper extends Component {
    constructor(props) {
      super(props);
      let storage = sessionStorage.getItem(this.props.match.url)
      if(storage) {
        this.state = JSON.parse(storage)
      } else {
        this.state = {
          page: 1,
          size: 10,
          sort: { dataIndex: 'id', order: 'desc' },
          loading: false,
          search: {},
        };
      }
    }

    componentWillMount() {
      // 组件即将渲染的时候拉取数据
      if(!opts.lazyRequest) {
        this.refresh()
      }
    }

    fetch() {
      let that = this;
      let params = {
        page: this.state.page - 1,
        size: this.state.size,
        sort: this.state.sort.dataIndex + ',' + this.state.sort.order
      }
      Object.assign(params, this.state.search)
      this.props.updateBindingData('instances', {
        params
      }, function () {
        that.setState({ loading: false });
        sessionStorage.setItem(that.props.match.url, JSON.stringify(that.state));
      });
    }

    filter(search) {
      this.setState({
        search,
        page: 0,
      })
      this.refresh();
    }

    handlePaginationChange = (page) => {
      this.setState({
        page
      });
      // 翻页时，拉取数据
      this.refresh();
    }

    handlePageSizeChange = (size) => {
      this.setState({
        size
      });
      this.refresh();
    }

    handleSort = (dataIndex, order) => {
      let sort = { dataIndex: dataIndex, order: order }
      this.setState({
        sort: sort,
      });
     this.refresh();
    }

    refresh = () => {
      this.setState({
        loading: true
      })
      setTimeout(()=>this.fetch(), 1);
    }

    deleteConfirm = (item, callback) => {
      let that = this;
      let okCallback = callback || function(item){return new Promise(resolve => {setTimeout(resolve, 200); })} 
      Dialog.confirm({
        title: '',
        content: '确认要删除吗?',
        onOk: () => {
          okCallback(item).then(() => {
            Message.success('操作成功!');
            that.refresh();
          });
        }
      });
    }

    render() {
      let that = this;
      const props = {
        ...this.props,
        ...this.state,
        styles: styles,
        fetch: this.fetch.bind(that),
        filter: this.filter.bind(that),
        handleSort: this.handleSort,
        handlePaginationChange: this.handlePaginationChange,
        handlePageSizeChange: this.handlePageSizeChange,
        deleteConfirm: this.deleteConfirm,
      }
      return <WrappedComponent {...props} />
    }
  }

  return SearchTableWrapper
}

const styles = {
  container: {
    margin: '20px',
    padding: '0 0 20px',
  },
  title: {
    margin: '0',
    padding: '15px 20px',
    fonSize: '16px',
    textOverflow: 'ellipsis',
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    color: 'rgba(0,0,0,.85)',
    fontWeight: '500',
    borderBottom: '1px solid #eee',
  },
  link: {
    margin: '0 5px',
    color: 'rgba(49, 128, 253, 0.65)',
    cursor: 'pointer',
    textDecoration: 'none',
  },
  separator: {
    margin: '0 3px',
    display: 'inline-block',
    height: '12px',
    width: '1px',
    verticalAlign: 'middle',
    background: '#e8e8e8',
  },
  pagination: {
    textAlign: 'right',
    marginRight: '20px',
  },
  editIcon: {
    color: '#2874D1',
    cursor: 'pointer',
  },
  horizontal: {
    dl: {
      margin: '0',
    },
    dt: {
      float: 'left',
      width: '60px',
      overflow: 'hidden',
      clear: 'left',
      textAlign: 'right',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
    },
    dd: {
      marginLeft: '70px',
    }
  }
};